//
//  JHSNetworkingTool.m
//  病例管理
//
//  Created by chenWei on 2017/3/24.
//  Copyright © 2017年 陈伟. All rights reserved.
//

#import "JHSNetworkingTool.h"
#import "AFNetworking.h"

@implementation JHSNetworkingTool

+ (instancetype)shareManager
{
    static JHSNetworkingTool *manager = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        
        manager = [[self alloc] init];
        
    });
    
    return manager;
    
}


- (void)postWithURLStr:(NSString *)urlStr withParameters:(id)parameters withSuccessBlock:(void (^)(id))successBK withFailureBlock:(void (^)(NSError *))failureBK
{
    AFHTTPSessionManager *manager = [self afhConfig];

    NSString *url = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //发起 post 请求
    [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //如果成功则把获取到的数据原封不动的传过去
        successBK(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //传输不成功把出现的错误返回回去
        failureBK(error);
    }];
    
}

- (void)getWithURLStr:(NSString *)urlStr withParameters:(id)parameters withSuccessBlock:(void (^)(id))successBK withFailureBlock:(void (^)(NSError *))failureBK
{
    AFHTTPSessionManager *manager = [self afhConfig];
    
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    NSLog(@"======%@",urlStr);
    
    [manager GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"######%@",responseObject);
        
        successBK(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failureBK(error);
    }];
    
}


//设置 AFHTTPSessionManager 属性
- (AFHTTPSessionManager *)afhConfig
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置请求时长
    manager.requestSerializer.timeoutInterval = 60;
    
    //设置可接受的响应数据格式
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    //支持向服务器post json 的二进制数据
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    return manager;
}

@end
